package com.zpark.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.json.JSONUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.zpark.FeignClient.UserModelFeignClient;
import com.zpark.common.R;
import com.zpark.entity.User;
import com.zpark.util.DateUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private UserModelFeignClient userModelFeignClient;

    @Value("${fdfs.http}")
    private String FDFS_HTTP;
    @Value("${fdfs.host}")
    private String FDFS_HOST;
    @Value("${fdfs.port}")
    private String FDFS_PORT;

    @RequestMapping("/loginUser")
    public R loginUser(String username,String password,String code, HttpSession session){
        String oldCode = (String) session.getAttribute("oldCode");
        if(oldCode.toUpperCase().equals(code.toUpperCase())){
            R r = userModelFeignClient.loginUser(username, password);
            session.setAttribute("user",r.get("data"));
            return r;
        }else{
            return R.error(1,"验证码输入不一致！");
        }
    }

    @RequestMapping("/queryAllUser")
    public R queryAllUser(Integer page,Integer limit){
        return userModelFeignClient.queryUserByPage(null,null,page, limit);
    }

    @RequestMapping("/queryUserById")
    public R queryUserById(Integer id){
        return userModelFeignClient.queryUserById(id);
    }

    @RequestMapping("/searchUser")
    public R searchUser(String column,String value,Integer page,Integer limit){
        if("sex".equals(column)&&("男").equals(value)){
            value = "1";
        }
        if("sex".equals(column)&&("女").equals(value)){
            value = "0";
        }
        return userModelFeignClient.queryUserByPage(column,value,page,limit);
    }
    /**
     * FastDFS实现文件上传
     * */
    @RequestMapping("/uploadHead")
    public R upload(MultipartFile file){
        String url = FDFS_HTTP+"://"+FDFS_HOST+":"+FDFS_PORT+"/";
        InputStream is = null;
        try{
            is = file.getInputStream();
            StorePath storePath = fastFileStorageClient.uploadFile(is, file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
            String fullPath = storePath.getFullPath();
            return R.ok().put("picPath",url+fullPath);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try{
                if(is!=null)is.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/addUser")
    public R addUser(User user){
        Map<String,Object> map = new HashMap<>();
        map.put("name",user.getName());
        map.put("password",user.getPassword());
        map.put("sex",user.getSex());
        map.put("photo",user.getPhoto());
        map.put("birthDay", DateUtil.utilDateToStringDate(user.getBirthDay()));
        map.put("email",user.getEmail());
        return userModelFeignClient.addUser(map);
    }

    @RequestMapping("/amendUser")
    public R amendUser(User user){
        Map<String,Object> map = new HashMap<>();
        map.put("id",user.getId());
        map.put("name",user.getName());
        map.put("password",user.getPassword());
        map.put("sex",user.getSex());
        map.put("photo",user.getPhoto());
        map.put("birthDay",DateUtil.utilDateToStringDate(user.getBirthDay()));
        map.put("email",user.getEmail());
        return userModelFeignClient.amendUser(map);
    }

    @RequestMapping("/dropUserById")
    public R dropUserById(Integer id){
        return userModelFeignClient.dropUserById(id);
    }

    @RequestMapping("/dropUserByIds")
    public R dropUserById(Integer[] ids){
        return userModelFeignClient.dropUserByIds(ids);
    }

    @RequestMapping("/createCode")
    public void createCode(HttpServletResponse response, HttpSession session){
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            captcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        session.setAttribute("oldCode",captcha.getCode());
    }

    @RequestMapping("/welcome")
    public R welcome(HttpSession session){
        Map user = (Map) session.getAttribute("user");
        return R.ok().put("data",user);
    }

    @RequestMapping("/exitUser")
    public R exitUser(HttpSession session){
        session.removeAttribute("user");
        return R.ok();
    }

    @RequestMapping("/importExcel")
    public R importExcel(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<User> users = ExcelImportUtil.importExcel(file.getInputStream(), User.class, importParams);
        String[] jsonList = new String[users.size()];
        for(int i=0;i<users.size();i++){
            String userJson = JSONUtil.toJsonStr(users.get(i));
            jsonList[i] = userJson;
        }
        return userModelFeignClient.addAllUser(jsonList);
    }

    @RequestMapping("/exportExcel")
    public void exportExcel(Integer[] ids,HttpServletResponse response) throws Exception {
        R r = userModelFeignClient.queryUserByIds(ids);
        List<Map> maps = (List<Map>) r.get("data");
        List<User> users = new ArrayList<>();
        for (Map map : maps) {
            String jsonStr = JSONUtil.toJsonStr(map);
            User user = JSONUtil.toBean(jsonStr, User.class);
            users.add(user);
        }
        ExportParams exportParams = new ExportParams("用户数据信息", "sheet1");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, users);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-disposition","attachment;filename=user_"+new Date().getTime()+".xls");
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/exportExcelAll")
    public void exportExcelAll(HttpServletResponse response) throws IOException {
        R r = userModelFeignClient.queryAllUser();
        List<Map> maps = (List<Map>) r.get("data");
        List<User> users = new ArrayList<>();
        for (Map map : maps) {
            String jsonStr = JSONUtil.toJsonStr(map);
            User user = JSONUtil.toBean(jsonStr, User.class);
            users.add(user);
        }
        ExportParams exportParams = new ExportParams("用户数据信息", "sheet1");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, users);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-disposition","attachment;filename=user_"+new Date().getTime()+".xls");
        workbook.write(response.getOutputStream());
        users.forEach(System.out::println);
    }

    @RequestMapping("/queryUserSexCount")
    public R queryCountBySex(){
        return userModelFeignClient.queryUserSexCount();
    }


}
